package db

import (
	"center/db/models"
	"common/node_pieces"
	"common/uuid"
	"context"
)

func (d *CenterDB) GetSegments(ctx context.Context, streamId uuid.UUID, index int) (result *models.Segment, err error) {
	err = d.db.WithContext(ctx).Where("stream_id = ? and position = ?", streamId, index).Take(&result).Error
	return
}

func (d *CenterDB) GetSegmentByStreamIdAndPosition(ctx context.Context, streamId uuid.UUID, position int) (result *models.Segment, err error) {
	err = d.db.WithContext(ctx).Where("stream_id = ? and position = ?", streamId, position).Take(&result).Error
	return
}

type CommitSegmentParam struct {
	StreamId   uuid.UUID
	Position   int
	PieceNum   uint8
	NodePieces node_pieces.NodePieces
	Pad        int
	PlainSize  int64
}

func (d *CenterDB) CommitSegment(ctx context.Context, param *CommitSegmentParam) (segment *models.Segment, err error) {
	segment = &models.Segment{
		StreamId:   param.StreamId,
		Position:   param.Position,
		PieceNum:   param.PieceNum,
		NodePieces: param.NodePieces,
		Pad:        param.Pad,
		PlainSize:  param.PlainSize,
		Folded:     param.NodePieces.Folded(),
	}
	err = d.db.WithContext(ctx).Create(&segment).Error
	return
}
func (d *CenterDB) UpdateSegmentNodePieces(ctx context.Context, param *CommitSegmentParam) error {
	err := d.db.WithContext(ctx).Where("stream_id = ? and position = ?",
		param.StreamId, param.Position).UpdateColumns(map[string]any{
		"node_pieces": param.NodePieces,
		"folded":      param.NodePieces.Folded(),
	}).Error
	return err
}

// GetSegmentsForRepairCheck 获取segment 去检查是否需要修复
func (d *CenterDB) GetSegmentsForRepairCheck(ctx context.Context, lastId int64, limit int) (segs []*models.Segment, err error) {
	segs = make([]*models.Segment, 0, limit)
	err = d.db.WithContext(ctx).Model(models.Segment{}).
		Where("id > ? and status = ? ", lastId, models.StatusNormal).
		Order("id asc").Limit(limit).Find(&segs).Error
	return
}
